package com.iris.live.services.services.impl;

import com.iris.live.services.common.StringUtils;
import com.iris.live.services.common.reconsitution.ExcelAnalysisUtil;
import com.iris.live.services.data.models.TFileInfoLogModel;
import com.iris.live.services.data.repositories.TFileInfoLogRepository;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.CustomerInfoService;
import com.iris.live.services.services.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lusong on 2017/6/23.
 */
@Service
public class FileServiceImpl implements FileService {

    private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private Environment env;

    @Autowired
    private TFileInfoLogRepository tFileInfoLogRepository;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData dataMoveLeaningInList(String permit, String fileName, String filePath, String username) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (StringUtils.isNullOrBlank(fileName)) {
            logger.error("ilog数据迁移表名参数为空");
            resultData.setMessage("ilog数据迁移表名参数为空");
        } else {
            tFileInfoLogRepository.deleteModelByPermit(permit);
            TFileInfoLogModel tFileInfoLogModel = saveTFileInfoLog(null, permit, "导入名单", fileName, filePath, "0", null, username);
            if (tFileInfoLogModel != null) {
                resultData.setResult("true");
            }
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData dataMoveCusRecordPool(String permit, String fileName, String filePath, String username) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (StringUtils.isNullOrBlank(fileName)) {
            logger.error("ilog数据迁移表名参数为空");
            resultData.setMessage("ilog数据迁移表名参数为空");
        } else {
            TFileInfoLogModel tFileInfoLogModel = saveTFileInfoLog(null, permit, "顾客记录汇总", fileName, filePath, "0", null, username);
            if (tFileInfoLogModel != null) {
                resultData.setResult("true");
            }
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData dataMoveCusIntoTheStoreAndTestDrive(String permit, String fileName, String filePath, String username) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (StringUtils.isNullOrBlank(fileName)) {
            logger.error("ilog数据迁移表名参数为空");
            resultData.setMessage("ilog数据迁移表名参数为空");
        } else {
            TFileInfoLogModel tFileInfoLogModel = saveTFileInfoLog(null, permit, "接待记录", fileName, filePath, "0", null, username);
            if (tFileInfoLogModel != null) {
                resultData.setResult("true");
            }
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void readExcel (String permit, String filePathTXT) throws Exception {
        ResultData resultData = null;
        String type = null;
        try {
            List<TFileInfoLogModel> list = tFileInfoLogRepository.queryUnreadFile(permit);
            if (list != null && !list.isEmpty()) {
                for (TFileInfoLogModel tFileInfoLogModel : list) {
                    if (tFileInfoLogModel != null) {
                        Map map = null;
                        List<Map> listMap = null;

                        String filePath = env.getProperty("upload.excel.dir") + tFileInfoLogModel.getFilePath();
                        File file = new File(filePath);

                        if ("导入名单".equals(tFileInfoLogModel.getType())) {
                            type = "导入名单";
                            map = ExcelAnalysisUtil.validExcelFile(file, ExcelAnalysisUtil.XML_NODENAME_ILOG_TRANSFER_LEADINGIN);
                            if (map != null) {
                                listMap = (List<Map>) map.get("list");
                                resultData = customerInfoService.dataMoveLeaningInListOverWrite(permit, listMap);
                            }
                        } else if ("顾客记录汇总".equals(tFileInfoLogModel.getType())) {
                            type = "顾客记录汇总";
                            map = ExcelAnalysisUtil.validExcelFile(file, ExcelAnalysisUtil.XML_NODENAME_ILOG_TRANSFER_CUSRECORDPOOL);
                            if (map != null) {
                                listMap = (List<Map>) map.get("list");
                                resultData = customerInfoService.dataMoveCusRecordPoolOverWrite(permit, listMap);
                            }
                        } else if ("接待记录".equals(tFileInfoLogModel.getType())) {
                            type = "接待记录";
                            map = ExcelAnalysisUtil.validExcelFile(file, ExcelAnalysisUtil.XML_NODENAME_ILOG_TRANSFER_CUSINTOTHESTOREANDTESTDRIVE);
                            if (map != null) {
                                listMap = (List<Map>) map.get("list");
                                resultData = customerInfoService.dataMoveCusIntoTheStoreAndTestDriveOverWrite(permit, listMap);
                            }
                        }
                        if (resultData != null && "true".equals(resultData.getResult())) {
                            tFileInfoLogModel.setState("1");
                            if (!StringUtils.isNullOrBlank(resultData.getMessage())) {
                                String message = writeFile(resultData.getMessage(),filePathTXT, true);
                                tFileInfoLogModel.setMessage(message);
                            }
                        }
                    }
                }
                tFileInfoLogRepository.save(list);
            }
        } catch (Exception e) {
            logger.error(type + "--数据迁移失败", e);
            throw new Exception(e);
        }
    }

    public String writeFile(String content, String filePath, boolean flag) {
        try {
            File f = new File( env.getProperty("upload.excel.dir") + filePath);
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f, flag));
            BufferedWriter writer = new BufferedWriter(write);
            writer.write("\n\n" + content);
            writer.flush();
            write.close();
            writer.close();
            logger.debug("Write File message");
        }catch (Exception e){
            logger.error("iLog数据迁移生成TXT程序异常", e);
        }
        return filePath;
    }

    private TFileInfoLogModel saveTFileInfoLog (TFileInfoLogModel tFileInfoLogModel,String permit, String type,
                                                String fileName, String filePath, String state, String message, String username) {
        if (tFileInfoLogModel == null) {
            tFileInfoLogModel = new TFileInfoLogModel();
        }
        if (!StringUtils.isNullOrBlank(permit)) {
            tFileInfoLogModel.setPermit(permit);
        }
        if (!StringUtils.isNullOrBlank(type)) {
            tFileInfoLogModel.setType(type);
        }
        if (!StringUtils.isNullOrBlank(fileName)) {
            tFileInfoLogModel.setFileName(fileName);
        }
        if (!StringUtils.isNullOrBlank(filePath)) {
            tFileInfoLogModel.setFilePath(filePath);
        }
        if (!StringUtils.isNullOrBlank(state)) {
            tFileInfoLogModel.setState(state);
        }
        if (!StringUtils.isNullOrBlank(message)) {
            tFileInfoLogModel.setMessage(message);
        }
        if (!StringUtils.isNullOrBlank(username)) {
            tFileInfoLogModel.setUpdateAccount(username);
        }
        tFileInfoLogModel.setUpdateTime(new Timestamp(new Date().getTime()));
        return tFileInfoLogRepository.save(tFileInfoLogModel);
    }

    public void downloadTxt (String permit, HttpServletResponse response) throws Exception {
        List<TFileInfoLogModel> list = tFileInfoLogRepository.queryNewModelByPermit(permit);
        if (list != null && !list.isEmpty()) {
            String filePath = env.getProperty("upload.excel.dir") + list.get(0).getMessage();
            if (!StringUtils.isNullOrBlank(filePath)) {
                downlod(response, filePath);
            }
        }
    }

    private void downlod (HttpServletResponse response, String fileName) throws IOException {
        File file =  new File(fileName);
        if(file.exists()){
            String path = env.getProperty("upload.excel.dir") + "download.txt";
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename=" + path);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] by  = new byte[fileInputStream.available()];
            fileInputStream.read(by);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(by);
            fileInputStream.close();
            outputStream.close();
        }
    }
}
